/**
 * 多客服聊天系统-客服端
 * 当前版本由jQuery 书写，可以运行在PC版
 * @author 晓风<215628355@qq.com> 
 *
**/

//默认图片地址处理
function noFind(img){ 
    img.src = '/static/customer/images/face.png'  // 默认图片地址
    img.onerror = null;  // 控制不要循环展示错误
}
//socket主线业务,依赖于socket.io插件
var sockets = {
    socket : null,
    user : {},
    clientHeader : 0,
    clientConnHeader : 0,
    chatConnHeader : 0, 
    autoReplay : '',
	upToken : "",     
    notifyMusic : 0,  //消息通知 
    client : function(url,user,token){
        var that = this;
		that.upToken = token;
        
        var index = layer.load(0, {shade: [0.01,'#000']});
        that.socket = new io(url,{
            transports: [ 'websocket']  
        });//初始化socket.io
        that.socket.on('connect', function() {
            console.log("连接成功"); 
            if(that.chatConnHeader  == 0){                
                that.socket.emit("conn",user)
                that.chatConnHeader = 1;
            }
            that.clientHeader = 1;
            that.error("连接到服务器");
            layer.close(index)
        });
        that.socket.on('reconnect', function() {	
            //console.log("重新连接到服务器");            
            that.clientHeader = 1;
            that.error("重新连接到服务器");
            layer.close(index)
        });
        that.socket.on("disconnect",function(){
           // console.log("与服务器断开")
            that.clientHeader = 0;
            that.error("与服务器断开");            
            index = layer.load(0, {shade: [0.01,'#000'],  content: '<br />已断开', });  
        })
        that.socket.on('heartbeat', function () {
            that.socket.emit("heartbeat","heartbeat");
        });
        that.socket.on("broadcastingListen",function(data){        
            for(var i=0; i< data.length; i++){
                var MESSAGE = data[i];
                console.log(MESSAGE)
                that.useMessage(MESSAGE);
            }
        })       
        that.socket.on("conn",function(code){
            if(code[0]  == "ok"){                
                //console.log("私信注册成功",code[0])
                that.error("注册客服服务成功");
                that.clientConnHeader = 1;
                that.init();                
            }else{                
                that.error("注册客服服务失败");
            }           
        })                
        this.user = user;
    },
    //初步分解消息
    useMessage : function(data){
        var that = this;
        var json = this.evealJson(data);       
   
        var metch = json.type;
		//如果客服不是我，则这条消息排除，不展示
		//在客服会话中，如果不加这个判断，会非常混乱
		if(data.service_user_id != that.user.uid){
			return false;
		}
        
        //有时候会自己和自己聊，这个要排除下，接收到本端发的消息不要渲染
        if(data.user_id == that.user.uid  && data.form_type == 2){
			return false;
		}       
       
        switch(metch){            
            case "recall":            
				that.recallMessage(json); 
				break;            
            default:			
				that.loadMsg(json);   
				break;
        }
    },
    //解析JSON
    evealJson:function(data){  
        if(typeof data != 'object'){    
            try{        
                data  = JSON.parse(data);
            }catch(err){          
                //console.log('JSON解析错误',err );
                return !1;          
            }  
        }  
        return data;    
    },
    //加载一个普通消息，放到左列
    loadMsg: function(data){       
        var oDate = new Date(data.create_time);         
        var time = oDate.getHours() + ":" + oDate.getMinutes() 
		var uuid = data.user_id + "-" + data.store_id;
        var size =  $(".users li[uuid='"+ uuid +"']").size();
        var hasAvtive = false;
        if(size >0){
            hasAvtive = $(".users li[uuid='"+ uuid +"']").hasClass("active");
        }
        var className = hasAvtive ? "avtive" : "noread";
		console.log('message',data)
        //更新会话    
        var html = `<li uuid="${uuid}" class="noread">
					<img src="${data.head_img}" onerror="noFind(this)">
						<div class="infos"><h4>${data.nickname}</h4>
						<div class="text">${data.session_title}</div>
					</div>
					<div class="time">${time}</div>
					<i class="tip"></i>
				</li>`;
				
				// <div class="store label label-info">${data.store_name}</div>
        var box = $(html);       
        $(".users li[uuid='"+ uuid +"']").remove();     
        $(".users ul").prepend(box)  
		//尝试加载右侧聊天框		
        this.rightLoad(data)       
        this.notify(data.nickname,data.head_img,data.session_title);//增加新消息提醒	
    },
    //尝试将头像放在右侧窗口顶部
    rightLoad : function(data){
		var uuid = data.user_id + "-" + data.store_id;
        var html =  $(".message-box .avatar").html();
        if(!html){        
            var box1 = $('<div uuid="'+data.uuid+'" class="avatar-user"><img src="'+data.head_img+'"  store="'+data.store_logo+'" onerror="noFind(this)" /><div class="infos"><h4>'+data.nickname+'</h4><div class="text label label-info">'+data.store_name+'</div></div></div>');        
            $(".message-box .avatar").append(box1);
        }
		//如果当前对话的是这个人，则将聊天内容放到右侧窗口
        var _uuid =  $(".message-box .avatar .avatar-user").attr("uuid");
        if(_uuid  == uuid){
            this.rightAdd(data,"left")   
        }         
    },
    //撤回消息
    recallMessage:function(data){
       
    },
	
	
	
	
     //将消息放在右侧窗口内
    rightAdd:function(data,leftRight){  
        var isid = $('.message-box .message ul li[msgid="'+data.msgid+'"]').size(); //排除消息重复渲染
        if(isid > 0){
            return false;
        }    
        var content = this.loadContent(data.type,data.content) ;//解析消息体
        var box = $('<li msgid="'+data.msgid+'" class="'+leftRight+'" ><img src="'+data.head_img+'" class="user-face" onerror="noFind(this)" />'+content+'</li>');              
        $(".message-box .message ul").append(box);
        this.scrollbarBottom()
    },
    //解析消息体
    loadContent: function(action,ct){      
        action /=1;
        console.log(action)
        switch(action){
			//文字
			case 0:
			  ct = this.replaceFace(ct)
			  return `<div class="infos">${ct}</div>`;
			 //图片
            case 1 :    
			  return `<div class="infos picture"><img src="${ct}" onerror="noFind(this)" /><div class="remark">双击图片放大</div></div>`;
			  
			//视频
            case 2 :
              return `<div class="infos video"><video src="${ct}" controls="controls" preload="auto" controlsList="nofullscreen nodownload noremote footbar"  /></div>`;
             //商品
			case 3:
				var goods = JSON.parse(ct);
				return  `<div class="infos infos-goods">
					<div class="goods" data-gid="${goods.goods_id}" data-sku="${goods.sku_id}">
						<img src="${goods.thumb}" class="goods-img" onerror="noFind(this)" />
						<div class="goods-info">
							<h6>${goods.name}</h6>
							<div class="info">${goods.sku}</div>
							<div class="price">￥${goods.price}</div>
							<div class="remark">商品</div>
						</div>
					</div>
				</div>`;  
			//订单            
            case 4 :     
			 var order = JSON.parse(ct);			
             var html = `<div class="infos infos-order">      
                    <div class="order" data-sn="${order.order_sn}">                      
                    <div class="icon">
                       <i class="glyphicon glyphicon-file"></i>${order.order_sn} [${order.status}]                    
                    </div>
                    <table class="order-goods table">`;
                    
                        order.goods.forEach(function(good){
                            html+=`
                             <tr>
                                <td class="thumb"><img src="${good.goods_thumb}" /></td>
                                <td>
                                    <div class="title">${good.goods_name}</div>
                                    <div class="sku">${good.sku_name}</div>                                                           
                                </td>
                                <td class="num">X ${good.num} </td>
                                <td class="price">￥${good.goods_money}</td>
                            </tr>`; 
                        })         
                                         
                    html+=`</table>
                    <div class="info">
                        <div class="text-right">应付： <font color="red">￥${order.payable_money}元</font></div>                                             
                        <div class="address">
                           ${order.info.receiver_name} ${order.info.receiver_mobile}
                           ${order.info.province} ${order.info.city} ${order.info.district} ${order.info.receiver_address}
                        </div>
                        <div class="remark">${order.info.remark}</div>                        
                    </div>
                    <div class="remark mt10">订单</div>
                </div>`; 
            return html;
              
           default:  
                return `<div class="infos">${ct}</div>`;
        }
        
    },    
    //替换文字中的表情与换行
    replaceFace : function(content){        
        content = content.replace(/\r\n/g,"<br>")  
        content = content.replace(/\n/g,"<br>"); 
        content = ShopsFace.replaceFace(content);        
        return content;
    },
    //连接成功初始化
    init :function(){
        var that = this;
        that.getUsers(that.user.uid,1,"#user1",true);
        that.getUsers(0,1,"#user2",false);
        $("#submit").unbind();
        $(".users ul li").unbind();
        $("#submit").click(function(){
            var input = $.trim($(".message-txtarea-input").val())
            if(!input){
                return;
            }
            var uuid =  $(".message-box .avatar .avatar-user").attr("uuid");
            if(!uuid){
                return;
            }   
            $(".message-txtarea-input").val("")
            that.sendMsg(uuid,input)
        })
		 $(document).on('click','#message-mobile-back',function(){		
			$('#message-mobile-info').show();
			$('#message-mobile-msg').hide();
		 })
         $(document).on('click','.message-box .avatar .avatar-user .delete',function(){
             
            var uuid =  $(".message-box .avatar .avatar-user").attr("uuid")   
			var _uuid = uuid.split("-")	
            $.post("/index.php/customer/message/del_store_session", {store_id:_uuid[1],user_id:_uuid[0]} ,function(result){
                if(result.code == 1){       
                    $(".users ul li[uuid='"+uuid+"']").remove();
                    $(".message-box .avatar").html("")  
                    $(".message-box .message ul").html("") 
                    $('#message-mobile-info').show();
                    $('#message-mobile-msg').hide();
                }else{                
                   layer.msg(result.msg);                 
                }
            })  
            return false;//阻止冒泡
        })
        
		$(document).on('click','.closess',function(){
		     
		    var uuid =  $(".message-box .avatar .avatar-user").attr("uuid")   
			var _uuid = uuid.split("-")	
		    $.post("/index.php/customer/message/del_store_session", {store_id:_uuid[1],user_id:_uuid[0]} ,function(result){
		        if(result.code == 1){       
		            $(".users ul li[uuid='"+uuid+"']").remove();
		            $(".message-box .avatar").html("")  
		            $(".message-box .message ul").html("") 
		            $('#message-mobile-info').show();
		            $('#message-mobile-msg').hide();
		        }else{                
		           layer.msg(result.msg);                 
		        }
		    })  
		    return false;//阻止冒泡
		})
        //查看资料
		$(document).on("click", ".message-box .avatar .avatar-user .user-view",function(){            
             var uuid =  $(".message-box .avatar .avatar-user").attr("uuid")       
			 var _uuid = uuid.split("-")	
			 layer.open({
				title: '查看资料',
				type: 2,
				area: ['500px', '300px'],
				fix: false, //不固定
				maxmin: true,
				content: '/index.php/customer/message/get_user_info?user_id=' + _uuid[0] + '&store_id='+_uuid[1],				
			});		 
            return false;//阻止冒泡			
        })  
		
        $(document).on('click','.users ul li',function(){
			$('#message-mobile-info').hide();
			$('#message-mobile-msg').show();
            $('.users ul li').removeClass("avtive")
            $(this).removeClass("noread");
            $(this).addClass("avtive")
           // console.log($(this).html())
            var data = {
                uuid : $(this).attr("uuid"),				
                head_img : $(this).find("img").attr("src"),
                nickname : $(this).find("h4").html(),   
			    store_name : $(this).find(".store").html(), 
			    store_logo : $(this).find("img").attr("store"),				
            };   
            var ck = $(this).parents('.users').hasClass('line');           
            if(ck){
                var box1 = $('<div uuid="'+data.uuid+'" class="avatar-user"><img src="'+data.head_img+'" store="'+data.store_logo+'" onerror="noFind(this)" /><div class="infos" style="display:none;"><h4>'+data.nickname+'</h4><div><span class="text label label-info">'+data.store_name+'</span><span class="delete label label-danger">删除</span><span class="user-view label label-warning">查看资料</span></div></div></div>');        
            }else{
                var box1 = $('<div uuid="'+data.uuid+'" class="avatar-user"><img src="'+data.head_img+'" store="'+data.store_logo+'" onerror="noFind(this)" /><div class="infos" style="display:none;"><h4>'+data.nickname+'</h4><div><span class="text label label-info">'+data.store_name+'</span><span class="user-view label label-warning">查看资料</span></div></div></div>');        
            }			
            $(".message-box .avatar").html("")
            $(".message-box .avatar").append(box1);
            $(".message-box .message ul").html("")    
			var _uuid = data.uuid.split("-")	
            that.getAjaxUserMessage(_uuid[0] , _uuid[1]);	       
            $(".tabs-right ul li:eq(0) a").tab('show');//关闭其他内容，只展示用户信息 
            that.getUserInfo(_uuid[0] , _uuid[1]);            
          
        })
        
         //选项卡被点击时触发
        $('.tabs-right ul li a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            var uuid =  $(".message-box .avatar .avatar-user").attr("uuid");  
			
			
			console.log(uuid,'ididididi')
            if(!uuid){
                return ;
            }
            uuid = uuid.split("-") 	
            var tabId = $(e.target).attr("href");
            if(tabId == "#tab5"){
                that.getOrderList(uuid[0] , uuid[1]);                       
            }
            if(tabId == "#tab6"){
                that.getGoodsList(uuid[0] , uuid[1]);                       
            }
        })   
      
        $(document).on("click", ".message-box .message ul li.loadmore",function(){            
            var uuid =  $(".message-box .avatar .avatar-user").attr("uuid")       
			uuid = uuid.split("-") 			
            that.getAjaxUserMessage(uuid[0] , uuid[1])            
        }) 
		 
		 
		 
        //监听客服转接
        $(document).on("click",".services .links",function(){
              var store_id =  $(this).attr("store_id")  
              if(!store_id){
                  layer.msg("store_id nof found");
                  return
              }
			  var _self = this;
			//询问框
			var index = layer.open({
			  title: '设置',
			  content:"请你选择你在该店铺的状态",
			  shadeClose: true,
			  //area: ['400px', '500px'],
			  btn: ['休息','在线','忙碌',"关闭弹窗"],
			  btn1: function(index, layero){				 
				   that.sendStatus(store_id,0)
				   $(_self).parents("li").find('.label').html('休息')
				   layer.close(index)
			  },
			  btn2: function(index, layero){
				   that.sendStatus(store_id,1)  
				   $(_self).parents("li").find('.label').html('在线')
				   layer.close(index)
			  },
			  btn3: function(index, layero){
				  that.sendStatus(store_id,2)      
				  $(_self).parents("li").find('.label').html('忙碌')
				  layer.close(index)
			  },
		  });
        })
        
        $(".message-txtarea-input").keyup(function(event){            
            e = event ? event :(window.event ? window.event : null);
            if(!e.shiftKey && !e.ctrlKey && e.keyCode === 13){ //排除与Shifit/Ctrl连按
                //执行的方法
                $("#submit").click()
            }
            //ctrl + enter 换行
            if(e.ctrlKey && e.keyCode === 13){
                
                $(this).val($(this).val() + "\n")
            }
        })     
		
		$(document).on("click","#tab7 .message_item ",function(event){
			var msg = event.target.lastChild.innerText
			var uuid =  $(".message-box .avatar .avatar-user").attr("uuid");
			
			console.log(uuid,'ddddddss')
			that.sendMsg(uuid,msg,0);
		})  

 
        $(document).on("dblclick",".message-box .message ul li .picture  img",function(){
            var src = $(this).attr("src")            
            that.showViewImage(src);
        })
        $(document).on("click","#showImageView .imgClose",function(){            
            $("#showImageView").hide();
        })       
		$(document).on("change","#picture input",function(){
			var _uuid =  $(".message-box .avatar .avatar-user").attr("uuid");
			if(!_uuid){		
				layer.msg("请在聊天开始后再操作")
				return;
			}
			var fp = $(this);
			var file = fp[0].files[0];
			var url = URL.createObjectURL(file);  
			var head_img = $(".message-box .avatar .avatar-user img").attr('store')			
			
			content = '<div class="infos picture"><img src="'+url+'" /><div class="loading"></div></div>';
			var box = $('<li msgid="" class="right" time="" ><img src="'+head_img+'" class="user-face" onerror="noFind(this)" />'+content+'</li>');              
			$(".message-box .message ul").append(box);			
			
			//layer.msg("上线中")
			that.scrollbarBottom()
			_uploadfile(file,'images',"image/png,image/jpg",function(result){
				console.log('ok',result)
				that.sendMsg(_uuid,result.path,1,'',function(data){					
					box.find("li").attr('msgid',data.msgid);
					box.find("li").attr('time',data.create_time);
					box.find(".loading").addClass("remark").removeClass('loading').html("双击图片放大");			
				});				
			},function(){
				box.find(".loading").addClass("loading-error").removeClass('loading').html("上传失败");						
			},null,null);
			$(this).val('')
		})
		$(document).on("change","#video input",function(){			
			var _uuid =  $(".message-box .avatar .avatar-user").attr("uuid");
			if(!_uuid){		
				layer.msg("请在聊天开始后再操作")
				return;
			}
			var fp = $(this);
			var file = fp[0].files[0];
			var url = URL.createObjectURL(file);  
			var head_img = $(".message-box .avatar .avatar-user img").attr('store')			
			
			content = '<div class="infos video"><video src="'+url+'" controls="controls" preload="auto" controlsList="nofullscreen nodownload noremote footbar" /><div class="loading"></div></div>';
			var box = $('<li msgid="" class="right" time=""><img src="'+head_img+'" class="user-face" onerror="noFind(this)" />'+content+'</li>');              
			$(".message-box .message ul").append(box);	

			var video = box.find('video').get(0);
			video.play()		
			//layer.msg("上线中")
			box.find('video').on("canplaythrough",function(e){		 
				console.log(this.duration)
				var time = this.duration;			
				_uploadfile(file,'file',"video/mp4",function(result){
					console.log('ok',result)
					that.sendMsg(_uuid,result.path,2,'',function(data){					
						box.find("li").attr('msgid',data.msgid);
						box.find("li").attr('time',data.create_time);
						box.find(".loading").remove();					
					});				
				},function(){
					box.find(".loading").addClass("loading-error").removeClass('loading').html("上传失败");			
								
				},time,null);
			})	
			that.scrollbarBottom()
			$(this).val('')
		})
        //当点击切换时，将离线消息移除
        $('[data-users] li').click(function(){
            var uuid =  $(".message-box .avatar .avatar-user").attr("uuid");
            $("#user1 ul li").each(function(i,e){
                 var uid = $(e).attr("uuid");
                 $("#user2 ul li[uuid='"+uid+"']").remove();
                 if(uuid == uid){                     
                    $('.users ul li').removeClass("avtive");                  
                    $(e).addClass("avtive");
                 }
            });
        })
        //发送订单
        $(document).on("click","[data-toggle='send-order']",function(){
            var order_sn = $(this).data("id");
            that.sendOrder(order_sn);
        })
          //发送订单
        $(document).on("click","[data-toggle='send-goods']",function(){
            var id = $(this).data("id");
            var skuid = $(this).data("sku");
            that.sendGoods(id,skuid);
        })
        if(that.notifyMusic > -1){
            layer.confirm('请点击确认开启声音提醒', {
                icon: 3, 
                title:'提示',
                yes: function(index){		
                    that.notifyMusic = 1;	
                    layer.close(index);  
                },
                cancel: function(index, layero){ 
                    layer.close(index);	
                } 
            });
        }
        //初始化左侧列表        
        this.getLeftInit();         
       
    },  

	
	
	

	sendStatus : function (store_id,_status){
		$.post("/index.php/customer/message/set_store_status", {store_id:store_id,status:_status} ,function(result){
			if(result.code == 1){       
			
			}else{                
			   layer.msg(result.msg);                 
			}
		})
	},
    //发消息
    sendMsg :function(uuid,msg,type,session_title , callback ){    
        if(!this.clientHeader){          
           layer.msg("你已下线")
           return false;
        }
        //私信没有注册
        if(! this.clientConnHeader){          
            window.location.reload();
            return false;
        }      
        var that = this;
		var _uuid = uuid.split("-");
        var type = type ? type : 0 ;    
		if(msg){
			msg = msg.replace(/<\/?.+?>/g, "");
		}
        // msg = msg.replace(/ /g, "");
        console.log(msg)
        if(!msg){
            return true;
        }
        var obj = {
			store_id:_uuid[1],
            user_id: _uuid[0],		   
            type:type,
            content: msg,  
			session_title : session_title ? session_title : ""
        };
        $.post("/index.php/customer/message/check_service_user", obj ,function(result){
            if(result.code == 1){   
			
				if( $.type(callback)  == "function"){
                    callback(result.data);
                } else{
					that.rightAdd(result.data,"right")
				}
                that.socket.emit("sendmsg",{uid:_uuid[0],msg:result.data})
            }else{                
               layer.msg(result.msg);                 
            }
        })
    },
    scrollbarBottom : function(){
        var top =  $(".message-box .message ul").height();
        $(".message-box .message").scrollTop(top)
    },
    //提示错误
    error : function(msg){
        
         var box3 = $('<li class="times">'+msg+'</li>');
         $(".message-box .message ul").append(box3);
         this.scrollbarBottom()        
    },
    getLeftInit : function(){
        var size =  $(".users ul li").size()
        if(size >0){
            $(".users ul li:eq(0)").click()
        }        
    }, 
	
	 //获取用户个人信息
	 getUserInfo:function(uid,store_id){
        $(".userdesc").find("span").html(""); //清除用户信息   
        
           
	 	var that = this
	 	$.post("/index.php/customer/message/get_user_info",{user_id:uid,store_id : store_id},function(result){
		    if(result.code == 1){   		   
				 $(".userdesc .right-id").html(result.data.id);
                 $(".userdesc .right-username").html(result.data.user_nickname);
                 $(".userdesc .right-usermobile").html(result.data.mobile);
                 $(".userdesc .right-ip").html(result.data.last_login_ip);                
	 	    }    
		             
	 	});
	 },
     //获取订单信息
     getOrderList : function(uid,store_id){
         $(".order_list").html(""); //清除订单信息
          
         $.post("/index.php/customer/message/get_order_litst",{user_id:uid,store_id : store_id},function(result){
		    if(result.code == 1){   
                var orders = "";
                result.data.forEach(function(orderinfo){
                orders +=`<div class="order_item1">
									<div class="top">
										<div class="t_left">订单号：${orderinfo.order_sn}</div>
										<div class="status">${orderinfo.status_at}</div>
									</div>
									<p class="time">${orderinfo.create_time}</p>
									<ul class="googs_list">`;
                                    var orderGoodsNum = 0;
                                    orderinfo.goods.forEach(function(good){
                                        orderGoodsNum += good.num;
                                        orders += `<li class="g_item">
                                                <div class="g_left">
                                                    <img src="${good.goods_thumb}" alt="">
                                                </div>
                                                <div class="g_right">
                                                    <p>${good.goods_name}</p>
                                                    <p>x ${good.num}</p>
                                                    <p>￥ ${good.goods_money}</p>
                                                </div>
                                            </li>`;
                                    })
									orders += `</ul>
									<div class="b">
										<p>共${orderGoodsNum}件 合计 ：￥${orderinfo.payable_money}</p>
										<span data-toggle="send-order" data-id="${orderinfo.order_sn}">发送</span>
									</div>
								</div>`;
                })
                $(".order_list").html(orders);
	 	    }    
		             
	 	});
         
     },
     //获取商品信息
     getGoodsList : function(uid,store_id){
         $(".show_goods_list").html(""); //清除商品信息 
         $.post("/index.php/customer/message/get_goods_litst",{user_id:uid,store_id : store_id},function(result){
		    if(result.code == 1){   		
                var goods = "";
				if(result.data.length>0){
					result.data.forEach(function(good){
					       goods +=`<div class="zj">
										<div class="zj_img">
											<img src="${good.thumb}"alt="">
										</div>
										<div class="zj_info">
											<p class="ellipsis2">${good.name}</p>
											<div class="num">
												<span>销量 ${good.sales_sum}</span>
												<span>库存 ${good.stock}</span>
											</div>
											<div class="bottom">
												<p>￥${good.shop_price}</p>
												<span data-toggle="send-goods" data-id="${good.id}"  data-sku="${good.sku_id}">发送</span>
											</div>
										</div>
					                  </div>`;
					})
					$(".show_goods_list").html(goods);
				}else{
					$(".show_goods_list").text('暂无信息');
				}
                
	 	    }    
		             
	 	});
     },
   
    //获取与指定会员的聊天记录
    getAjaxUserMessage : function(uid , store_id){ 
        var that = this;
        var msgid = $(".message-box .message ul li[msgid]:eq(0)").attr("msgid")
        $(".message-box .message ul li.loadmore").remove();
        var top1 =  $(".message-box .message ul").height(); 
        $.post("/index.php/customer/message/get_user_messages",{user_id:uid,store_id : store_id,msgid:msgid},function(result){
           if(result.code == 1){   		   
			 
               $.each( result.data,function(i,e){   
                    var leftRight = e.form_type == 2 ?  "right" : "left";
                    var content = that.loadContent(e.type,e.content) ;                
                    var box2 = $('<li msgid="'+ e.msgid +'" class="'+leftRight+'" time="'+e.create_time+'"><img src="'+e.head_img+'" class="user-face" onerror="noFind(this)"/>'+ content +'</li>');                       
                    $(".message-box .message ul").prepend(box2);  
               })    
               var top2 =  $(".message-box .message ul").height();              
               $(".message-box .message").scrollTop(top2 - top1)
           }    
           if(result.data.length >0){              
               var box3 = $('<li class="loadmore">查看更多消息</li>');    
               $(".message-box .message ul").prepend(box3);               
           }           
       });
    },
 
   
    //显示图片预览
    showViewImage : function(src){    
        var img = new Image();
        img.src = src;       
        img.onload = function(){
            var w = img.width;
            var h = img.height;
            var vw = $(window).width();
            var vh = $(window).height();
            var maxW = vw - 100;
            var maxH = vh - 100;
            if(w > maxW){              
                h = maxW / w * h;
                w = maxW;
            }
            if(h > maxH){              
                //w = maxH / h * w;
                h = maxH;
            }
            h +=30;
            
            $("#showImageView").css({
                width:w,
                height:h,
                left: (vw - w) / 2,
                top: (vh - h) / 2                
            });          
            $("#showImageView .imgView img").attr("src",src)        
            $("#showImageView").show();            
        }




    },
   //显示会员预览
    showViewUser : function(uid){
        
        
        
    },
    getUsers :function(uid , page , id ,is_delete){
        
         var that = this;
         page = page || 1;
         $.post("/index.php/customer/message/get_users_list",{user_id:uid,page:page},function(result){
           if(result.code == 1 && result.data.data.length > 0){  	
               $.each( result.data.data,function(i,e){   
                      var uuid = e.user_id + '-' + e.store_id;                
                      var html =`<li uuid="${uuid}" ${e.service_noread > 0 ? 'class="noread"' : ''} onmouseover="showcut(this)" onmouseout="hidecut(this)">
                                        <img src="${e.head_img}" store="${e.store_logo}" onerror="noFind(this)">
                                        <div class="infos">
											<h4>${e.nickname}</h4>											
                                            <div class="text">${e.content}</div>
                                           
                                        </div>
                                        <div class="time">${e.update_time_at}</div>
                                        <i class="tip"></i>
										<span class="closess hide">x</span>
                                    </li>`; 
									//在.text下面，先隐藏
									// <div>
									//     <span class="store label label-info">${e.store_name}</span>                                           
									// </div>
                     var size = $(id).find("ul li[uuid='"+uuid+"']").size();
                     if(size < 1){
                         $(id).find("ul").append(html);                        
                     }
               }) 
               if(result.data.current_page < result.data.last_page){
                   page = result.data.current_page  + 1;
                   that.getUsers(uid,page,id);
               }
           }   
        })           
     
    },
    
    
    //发送商品
    sendGoods : function(goods_id,sku_id){
        var that = this;
        var uuid =  $(".message-box .avatar .avatar-user").attr("uuid");
        if(!uuid){
            layer.msg("获取会话失败");
            return false;
        }
        //组合消息
        var msg = JSON.stringify({
            goods_id : goods_id, //商品ID
            sku_id   : sku_id //skuID
        });
        //发送消息
        that.sendMsg(uuid,msg,3);	
    },
    //发送订单
    sendOrder:function(order_sn){
        var that = this;
        var uuid =  $(".message-box .avatar .avatar-user").attr("uuid");
        if(!uuid){
            layer.msg("获取会话失败");
            return false;
        }
        //组合消息
        var msg = JSON.stringify({
            order_sn : order_sn,   
        });
        //发送消息
        that.sendMsg(uuid,msg,4);		
    },
    //新消息提醒
	notifyObj : null,
	notifyTimeout : null,
	notify : function(nickname,head_img,content){
		var that = this;
		if(null !== that.notifyTimeout){
			clearTimeout(that.notifyTimeout);
		}	 		
		if(!that.notifyObj){
			that.notifyObj = new Notify({    
			  effect: "scroll", 
			  audio: {                       
				 file: '/static/customer/notify/chat.mp3'
			  },                     
			  interval: 2000,
			  disableFavicon: true,   			 
			});   
		}else{
			that.notifyObj.stopPlay();
			//that.notifyObj.faviconClear();
			that.notifyObj.setTitle(); 
		}		
			
		that.notifyObj.setTitle('【'+nickname+'】' + content); 
		that.notifyObj.notify({
		   title: nickname,
		   body: content,
		   icon : head_img,		 
		});				
		if( that.notifyMusic){
			that.notifyObj.player();                             
		}   
		
		that.notifyTimeout = setTimeout(function(){			
			that.notifyObj.stopPlay();
			//that.notifyObj.faviconClear();
			that.notifyObj.setTitle();
		},5000)
	}

}





